package com.beemans.topon.views

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.annotation.CallSuper
import androidx.lifecycle.LifecycleOwner
import com.beemans.topon.ads.TpSplashAd

/**
 * @author tiamosu
 * @date 2021/5/21.
 */
open class SplashAdLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
    private val exposureHelper by lazy { ExposureHelper() }

    var adLoader: TpSplashAd.TpSplashAdLoader? = null
        private set

    /**
     * 视图是否处于屏幕可见
     */
    val isLocalVisible: Boolean
        get() = exposureHelper.isLocalVisible

    init {
        exposureHelper.init(apply { }) { isVisible ->
            onAdVisible(isVisible)
        }
    }

    /**
     * 设置广告加载器
     */
    fun setAdLoader(adLoader: TpSplashAd.TpSplashAdLoader?) {
        this.adLoader = adLoader
    }

    /**
     * 加载广告
     */
    fun loadAd(
        owner: LifecycleOwner,
        config: TpSplashAd.TpSplashAdConfig,
        splashAdCallback: (TpSplashAd.TpSplashAdCallback.() -> Unit)? = null
    ) {
        if (adLoader == null) {
            adLoader = TpSplashAd.TpSplashAdLoader(
                owner = owner,
                config = config,
                flContainer = this,
                splashAdCallback = splashAdCallback
            )
        }
        adLoader?.let(TpSplashAd::start)
    }

    /**
     * 释放广告
     */
    fun onAdRelease() {
        adLoader?.onAdRelease()
        adLoader = null
    }

    @CallSuper
    open fun onAdVisible(isVisible: Boolean) {
    }
}